package weixin

import (
	"data/config"
	"data/view"
	"fmt"
	"net/http"
	"public/message"
	"public/mycache"
	"public/myhttp"
	"public/mysqldb"
	"public/weixin"
	"time"

	"github.com/silenceper/wechat"
)

var cfg wechat.Config

func init() {
	//使用memcache保存access_token，也可选择redis或自定义cache
	memCache := weixin.NewGocache("_winxin_access")

	tmp := config.GetWxInfo()
	//配置微信参数
	cfg = wechat.Config{
		AppID:          tmp.AppID,
		AppSecret:      tmp.AppSecret,
		Token:          tmp.Token,
		EncodingAESKey: tmp.EncodingAESKey,
		Cache:          memCache,
	}

}

func Index(w http.ResponseWriter, r *http.Request) {

	wc := wechat.NewWechat(&cfg)
	oauth := wc.GetOauth()

	r.ParseForm()
	state := r.Form["state"]
	random_code := r.Form["random_code"] //工作人员随机码
	url := r.Form["url"]                 //摇一摇

	if len(state) == 0 { //第一次跳转
		tmp := "oauth"
		if len(random_code) != 0 {
			tmp = random_code[0]
		}
		if len(url) != 0 {
			tmp = "shake"
		}
		err := oauth.Redirect(w, r, config.GetWxAuthorizeUrl(),
			"snsapi_userinfo", tmp) //授权
		if err != nil {
			fmt.Println(err)
		}
	} else {
		code := r.Form["code"]
		resToken, err := oauth.GetUserAccessToken(code[0])
		if err != nil {
			fmt.Println(err)
			return
		}
		//getUserInfo

		userInfo, err := oauth.GetUserInfo(resToken.AccessToken, resToken.OpenID)
		if err != nil {
			fmt.Println(err)
			return
		}
		var db mysqldb.MySqlDB
		defer db.OnDestoryDB()
		orm := db.OnGetDBOrm(config.GetDbUrl())

		var user_wx_info User_wx_info_tbl
		//判断保存用户微信信息
		orm.Where("open_id = ?", userInfo.OpenID).Find(&user_wx_info)
		if user_wx_info.Id == 0 {
			user_wx_info.City = userInfo.City
			user_wx_info.Country = userInfo.Country
			user_wx_info.Headimg_url = userInfo.HeadImgURL
			user_wx_info.Nick_name = userInfo.Nickname
			user_wx_info.Open_id = userInfo.OpenID
			user_wx_info.Province = userInfo.Province
			user_wx_info.Sex = userInfo.Sex
			orm.Create(&user_wx_info)

			//保存摇一摇信息
			var shake view.Shake_count_tbl
			shake.Open_id = userInfo.OpenID
			shake.Count = 1
			orm.Create(&shake)
		}
		if state[0] != "oauth" && state[0] != "shake" { //扫码游戏
			//先从缓存中获取
			cache := mycache.OnGetCache("scan")
			var tp interface{}
			tp, b := cache.Value(state[0])
			if b {
				tmp := tp.(User_wx_info_tbl)
				if tmp.Open_id == userInfo.OpenID {
					myhttp.WriteJson(w, message.GetErrorMsg(message.InValidOp, "重复扫码"))
					return
				}

			}
			//保存缓存
			cache.Add(state[0], user_wx_info, 10*time.Minute)
		}

		if state[0] != "shake" {
			//携带用户跳转排行榜页面
			w.Header().Set("Location", config.GetRank_url()+"?open_id="+userInfo.OpenID)
			w.WriteHeader(301)
		} else {
			//携带用户跳转摇一摇页面
			w.Header().Set("Location", config.GetShake_url()+"?open_id="+userInfo.OpenID)
			w.WriteHeader(301)
		}

		return
	}

}
